package com.etoak.service.impl;

import cn.hutool.core.date.DateUtil;
import cn.hutool.core.util.IdUtil;
import com.etoak.common.core.enuns.OrderStateEnum;
import com.etoak.common.core.vo.PageVO;
import com.etoak.common.web.context.LoginUserContext;
import com.etoak.config.OrderQueueConfig;
import com.etoak.dto.OrderDTO;
import com.etoak.entity.Order;
import com.etoak.mapper.OrderMapper;
import com.etoak.service.OrderItemService;
import com.etoak.service.OrderService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;

/**
 *  服务实现类
 *
 * @author etoak
 * @since 2025-08-28
 */
@Service
public class OrderServiceImpl extends ServiceImpl<OrderMapper, Order> implements OrderService {

    @Autowired
    OrderItemService orderItemService;

    @Autowired
    RabbitTemplate rabbitTemplate;

    @Transactional(rollbackFor = Exception.class)
    @Override
    public void create(OrderDTO orderDTO) {

        //订单编号
        String orderNo = IdUtil.getSnowflakeNextIdStr();

        Order order = new Order();
        order.setOrderNo(orderNo);
        order.setUserId(Integer.parseInt(LoginUserContext.getUserId()));
        order.setOrderState(OrderStateEnum.NEW.getValue());
        order.setPrepareTime(orderDTO.getPrepareTime());
        order.setCreateTime(DateUtil.now());
        save(order);

        // 给订单项设置订单编号
        orderDTO.getItemList().forEach(item -> item.setOrderNo(orderNo));
        //批量保存
        orderItemService.saveBatch(orderDTO.getItemList());

        //发送延迟消息
        rabbitTemplate.convertAndSend(OrderQueueConfig.EXCHANGE,
                OrderQueueConfig.KEY,
                orderNo,
                // 延迟 10s
                message -> {
                    message.getMessageProperties().setDelayLong(10 * 1000L);
                    return message;
                });
    }

    @Override
    public PageVO<Order> list(int pageNum, int pageSize) {
        PageHelper.startPage(pageNum, pageSize);
        List<Order> orderList = lambdaQuery().eq(Order::getUserId, LoginUserContext.getUserId()).list();
        PageInfo<Order> pageInfo = new PageInfo<>(orderList);
        return new PageVO<>(orderList, pageInfo.getTotal());
    }
}
